/**
 * QUANSHI.com Inc.
 * Copyright (c) 2016-2017 All Rights Reserved.
 */
package com.quanshi.scheduler.job.biz.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.quanshi.scheduler.job.biz.service.BaseService;
import com.quanshi.scheduler.job.biz.service.TriggerLogglueService;
import com.quanshi.scheduler.job.dal.dao.TriggerLogglueMapper;
import com.quanshi.scheduler.job.dal.entity.TriggerLogglue;
import com.quanshi.scheduler.job.dal.entity.TriggerLogglueExample;

/**
 * 
 * @author yanxiang.huang 2017-07-14 12:31:03
 */
@Service
public class TriggerLogglueServiceImpl extends BaseService implements TriggerLogglueService
{
    
    @Resource
    private TriggerLogglueMapper mapper;

    @Override
    public void deleteByJobId( long jobId )
    {
        TriggerLogglueExample query = new TriggerLogglueExample();
        query.createCriteria().andJobIdEqualTo( jobId );
        mapper.deleteByExample( query );
    }

    @Override
    public List<TriggerLogglue> findByJobId( long jobId )
    {
        TriggerLogglueExample query = new TriggerLogglueExample();
        query.setOrderByClause( "id desc" );
        query.createCriteria().andJobIdEqualTo( jobId );
        PageHelper.startPage( 1, 30 );
        return mapper.selectByExampleWithBLOBs( query );
    }

    @Override
    public void saveLog( long jobId, String glueType, String glueRemark, String glueSource )
    {
        TriggerLogglue log = new TriggerLogglue();
        log.setJobId( jobId );
        log.setGlueType( glueType );
        log.setGlueRemark( glueRemark );
        log.setGlueSource( glueSource );
        Date now = new Date();
        log.setAddTime( now );
        log.setUpdateTime( now );
        mapper.insert( log );
        
        removeOld(jobId);
    }

    /**
     * 删除超过30条的记录
     *
     * @param jobId
     */
    private void removeOld( long jobId )
    {
        List<TriggerLogglue> list = findByJobId( jobId );
        if (CollectionUtils.isNotEmpty( list ) && list.size() >= 30) {
            List<Long> ids = Lists.newArrayList();
            for ( TriggerLogglue log : list )
            {
                ids.add( log.getId() );
            }
            TriggerLogglueExample query = new TriggerLogglueExample();
            query.createCriteria().andIdNotIn( ids );
            mapper.deleteByExample( query );
        }
    }

}
